--waf core lib
require 'config'

--Get WAF rule
function get_rule(rulefilename)
    local io = require 'io'
    local RULE_PATH = config_rule_dir
    local RULE_FILE = io.open(RULE_PATH..'/'..rulefilename,"r")
    if RULE_FILE == nil then
        return
    end
    RULE_TABLE = {}
    for line in RULE_FILE:lines() do
        table.insert(RULE_TABLE,line)
    end
    RULE_FILE:close()
    return(RULE_TABLE)
end

--Get the client user agent
function get_user_agent()
    USER_AGENT = ngx.var.http_user_agent
    if USER_AGENT == nil then
       USER_AGENT = "unknown"
    end
    return USER_AGENT
end

function say_html(deny_type)
    ngx.header.content_type = "text/html"
    ngx.header["X-RateLimit-DenyType"] = deny_type 
    ngx.status = ngx.HTTP_FORBIDDEN
    ngx.say(html)
    ngx.exit(ngx.status)
end

function whiteip()
    local iputils = require("iputils")
    iputils.enable_lrucache()
    whitelist = iputils.parse_cidrs(ipWhitelist)
    if iputils.ip_in_cidrs(get_client_ip(), whitelist) then
      return true
    end
      return false
end

function blockip()
    local iputils = require("iputils")
    local client_ip = get_client_ip()
    iputils.enable_lrucache()
    whitelist = iputils.parse_cidrs(ipBlocklist)
    if iputils.ip_in_cidrs(client_ip, whitelist) then
      ngx.log(ngx.ERR, "block request ip: ", client_ip)
      return say_html("blockip")
    end
      return false
end

--Get the client IP
function get_client_ip()
    CLIENT_IP = ngx.req.get_headers()["X_real_ip"]
    if CLIENT_IP == nil then
        CLIENT_IP = ngx.req.get_headers()["X_Forwarded_For"]
    end
    if CLIENT_IP == nil then
        CLIENT_IP  = ngx.var.remote_addr
    end
    if CLIENT_IP == nil then
        CLIENT_IP  = "unknown"
    end
    return CLIENT_IP
end

function read_serlimit_config()
    local io = require 'io'
    local RULE_PATH = config_rule_dir
    local f = io.open(RULE_PATH..'/'..'servername_limit.rule',"r")
    if f == nil then
        return nil
    end
    ser_limit = {}
    ser_limit['ReqLimit'] = {}
    ser_limit['CountLimit'] = {}
    local section = nil
    for line in f:lines() do
       if line:find("ReqLimit") then
	   section = "ReqLimit"
       elseif line:find("CountLimit") then
           section = "CountLimit"
       else
	   servername = string.match(line, '[%a]+.[%a]+.[%a]+')
           serverlimit = string.match(line, '((%d+)/(%d+)/(%d+))') or string.match(line, '((%d+)/(%d+))')
	   ngx.log(ngx.ERR, serverlimit)
	   if servername and serverlimit then
	       if section == "ReqLimit" then
                   ser_limit["ReqLimit"][servername] = serverlimit
	       end
	       if section == "CountLimit" then
	           ser_limit["CountLimit"][servername] = serverlimit
	       end
	   end
       end
    end
    return ser_limit
end
